package net.fdukedom.epicurus.tools.mail;

import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.resource.ResourceDispatcher;
import net.fdukedom.epicurus.tools.config.Key;
import net.fdukedom.epicurus.tools.config.Configuration;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.MessagingException;
import javax.mail.Transport;
import java.util.Properties;
import java.util.Date;

/**
 * Mailing dispatcher.
 *
 * @author Dmitry Y. Kochelaev
 */
public class MailServer {

    /** Session used for sending messages. */
    private final Session session;

    /**
     * Creates a new mail server.
     */
    public MailServer() {
        Properties props = new Properties();
        props.put("mail.smtp.host",
                Configuration.getInstance().getStringValue(Key.MAIL_SMTP));
        this.session = Session.getInstance(props, null);
    }

    /**
     * Sends the message.
     * @param address the address to send the message to.
     * @param subject the subject of the message.
     * @param message the message to be send.
     * @throws MessageNotSentException if an error occured during message sending.
     */
    public void sendMessage(String address, String subject, String message)
            throws MessageNotSentException {
        if (address.indexOf('@') == -1) {
            throw new MessageNotSentException("Address must contain '@' character");
        }
        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(Configuration.getInstance().getStringValue(Key.MAIL_FROM)));
            msg.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse(address, false)
            );

            msg.setSubject(subject, Configuration.getInstance().getStringValue(Key.MAIL_ENCODING));
            msg.setText(message, Configuration.getInstance().getStringValue(Key.MAIL_ENCODING));

            msg.setHeader("X-Mailer", "Epicurus robot");
            msg.setSentDate(new Date());

            Transport.send(msg);
        } catch (MessagingException e) {
            throw new MessageNotSentException("Message was not send: " + e.getMessage(), e);
        }
    }
    
    /**
     * Sends activation email to user
     * @param user
     * @throws MessageNotSentException 
     */
    public void sendActivatioEMail(User user) throws MessageNotSentException {
        
        String code = UserHelper.getInstance().saveActivation(user);
        String msg = ResourceDispatcher.getInstance().getBundle("bundles.pub.Register").getString("pub.register.activationMail") + code; 
        sendMessage(user.getEmail(), "Activation", msg);
    }
}
